package angels.client.Services;	
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import angels.client.Entities.Business;
import angels.client.Listeners.BusinessListener;
import angels.client.Tasks.GetBusinessTask;
import angels.client.Tasks.SetSharingTask;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.ImageView;

public class BusinessService extends Service implements OnSharedPreferenceChangeListener{
	SharedPreferences prefs;
	String biskey;
	final IBinder mBinder = new LocalBinder();
    
	@Override
	public void onCreate(){
		super.onCreate();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(this);
		biskey=prefs.getString("bisKey", "ag9kZXZ-YW5nZWxzLWRlbW9yCgsSBEFyZWEYAQw");
	}
	
	public class LocalBinder extends Binder {
       public BusinessService getService() {
            return BusinessService.this;
        }
    }
	
	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}
	
	public String getBisURL(String biskey) {
		String server = prefs.getString("serverAddress", "http://angels-demo.appspot.com");
		return (server + "/get_business?bkey="+biskey).replace(" ", "%20");
	}

	public String setSharingURL(String username,String desc, Location location) {
	    String server = prefs.getString("serverAddress", "http://angels-demo.appspot.com");
	    try{
	    server+="/broadcast?user="  +username+
                "&loc=" + location.getLatitude() + "," + location.getLongitude() +
                "&desc=" + desc;
	    }
	    catch (Exception e){
	        Random generator = new Random();
	    	server+="/broadcast?user="  +username+
	                "&loc="+
	    			(0.18342+generator.nextDouble())
	                +","+
	    			(2.84591+generator.nextDouble())
	    			+" &desc=" + desc;
	    }
        return server.replace(" ", "%20");
    }
	 
	public synchronized void getBis(String username,BusinessListener listener){
		Timer getTimer = new Timer("Get timer");
		TimerTask timedGetTask = new GetBusinessTask(this,biskey,listener);
		getTimer.schedule(timedGetTask, 0);
	}
	
	public synchronized void setSharing(String username,String desc,BusinessListener listener){
		Timer sharingTimer = new Timer("Sharing timer");
		//TODO: check if we need to support to add share from here too
		//TimerTask timedSharingTask = new SetSharingTask(this,biskey,desc,listener);
		//sharingTimer.schedule(timedSharingTask, 0);
	} 
	
    //Notifies traffic updates to every activity that listens to the 
    public synchronized void notifyTraffic(Business bis, BusinessListener listener) {                
            listener.onUserInfoReceived(bis);
    }
    
    public synchronized void getUserImage(final ImageView image, String imageURL){
    	new FetchImageTask() { 
	        protected void onPostExecute(Bitmap result) {
	            if (result != null) {
	            	image.setImageBitmap(result);
	            }
	        }
	    }.execute(imageURL);
    }
    
    private class FetchImageTask extends AsyncTask<String, Integer, Bitmap> {
	    @Override
	    protected Bitmap doInBackground(String... arg0) {
	    	Bitmap b = null;
	    	try {
				 b = BitmapFactory.decodeStream((InputStream) new URL(arg0[0]).getContent());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
	        return b;
	    }	
	}
    
    public String getUsername(){
    	return biskey;
    }
    
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    	biskey=prefs.getString("bisKey", "ag9kZXZ-YW5nZWxzLWRlbW9yCgsSBEFyZWEYAQw");
	}
    
    @Override
    public void onDestroy () {
	    prefs.unregisterOnSharedPreferenceChangeListener(this);
    }
}